﻿using System;
using System.Text;
using System.Web.Http;
using log4net;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;
using Matrix.MaKaYunShang.Model.Wechat;

namespace Matrix.MaKaYunShang.ApiService.Controllers
{
    /// <summary>
    /// 微信相关API
    /// </summary>
    public class WeChatApiController : BaseApiController
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(WeChatApiController));
        private readonly BaseWxInterFunc _baseWxInterFunc = new BaseWxInterFunc();
        private MatrixCloudCenterInterFuncBll _matrixCloudCenterInterFuncBll = new MatrixCloudCenterInterFuncBll();
        // POST api/WeChatApi/GetAccessToken
        /// <summary>
        /// 根据McId获取AccessToken
        /// </summary>
        /// <param name="mcId">码云卡商户号</param>
        /// <param name="verifyCode">校验码</param>
        /// <returns>返回微信授权ACCESSTOKEN字符串</returns>
        [HttpPost]
        public Result<string> GetAccessToken(string mcId, string verifyCode)
        {
            var checkResult = CheckPermission("WeChatApiController | GetAccessToken");
            if (!checkResult.Status)
            {
                return checkResult;
            }

            #region 数据合法性检查
            if (string.IsNullOrWhiteSpace(verifyCode) || string.IsNullOrWhiteSpace(mcId))
            {
                _fileLog.Error("WeChatApiController | GetAccessToken | Error: Invalid paramter.");
                return new Result<string>
                {
                    Data = string.Empty,
                    Message = "Invalid paramter",
                    Status = false
                };
            }

            var strLocalEncodeResult = EncryptionLib.Encrypt(mcId, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("WeChatApiController | GetAccessToken | Error: Invalid verify code.");
                return new Result<string>
                {
                    Data = string.Empty,
                    Message = "Invalid verify code",
                    Status = false
                };
            }
            #endregion

            try
            {
                var projectInfo = GetCurrentMatrixCloudProjectInfo(mcId);
                if (projectInfo == null || projectInfo.Id == 0 || string.IsNullOrWhiteSpace(projectInfo.PjMcId) ||
                    string.IsNullOrWhiteSpace(projectInfo.PjSecret))
                {
                    return new Result<string>
                    {
                        Data = string.Empty,
                        Message = "Invalid mcId",
                        Status = false
                    };
                }

                var resultAccessToken = MatrixCloudCenterInterFuncBllObj.GetWechatMpAccessToken(projectInfo.PjMcId,
                    projectInfo.PjSecret);
                return resultAccessToken;

            }
            catch (Exception ex)
            {
                _fileLog.Error("WeChatApiController | GetAccessToken | Exception: " + ex.Message + ex.StackTrace);
                return new Result<string>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = string.Empty
                };
            }
        }

        /// <summary>
        /// 微信wx.config 配置信息
        /// </summary>
        /// <param name="mcId">mcId</param>
        /// <param name="absoluteUri">当前url</param>
        /// <returns></returns>
        [HttpPost]
        public Result<string> GetConfig(string mcId, string absoluteUri)
        {
            var checkResult = CheckPermission("WeChatApiController | GetConfig");
            if (!checkResult.Status)
            {
                return checkResult;
            }
            try
            {
                var matrixCloudProjectInfo = GetCurrentMatrixCloudProjectInfo(mcId);
                if (matrixCloudProjectInfo == null)
                {
                    return new Result<string>
                    {
                        Data = null,
                        Message = "WeChatApiController | GetConfig| ProjectInfo is null",
                        Status = false
                    };
                }
                var wechatInfo = GetWeChatInfoByMcId(matrixCloudProjectInfo);
                if (wechatInfo == null)
                {
                    return new Result<string>
                    {
                        Data = null,
                        Message = "WeChatApiController | GetConfig| wechatInfo is null",
                        Status = false
                    };
                }
                string nonstr = JsTicket.getnonstr(16);
                Result<string> jsapiTicket = _matrixCloudCenterInterFuncBll.GetWechatJsApiTicket(matrixCloudProjectInfo.PjMcId, matrixCloudProjectInfo.PjSecret);
                double timestamp = (DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;
                string signature = JsTicket.getSign(nonstr, jsapiTicket.Data,timestamp, absoluteUri);
                return new Result<string>
                {
                    Data = "{\"signature\":\"" + signature + "\" ,\"nonstr\":\"" + nonstr + "\",\"timestamp\":\"" + timestamp + "\",\"appId\":\"" + wechatInfo.AppId + "\"}",
                    Message = "Success",
                    Status = true
                };
            }
            catch (Exception ex)
            {

                return new Result<string>
                {
                    Data = null,
                    Message = ex.Message,
                    Status = false
                };
            }
        }

        /// <summary>
        /// 根据店铺id找到老板对应的带参数二维码
        /// </summary>
        [HttpPost]
        public Result<string> GetWechatParamQrCode(string mcId, int shopId, string verifyCode)
        {
            var result = new Result<string>();
            try
            {
                var checkResult = CheckPermission("WeChatApiController | GetWechatParamQrCode");
                if (!checkResult.Status)
                {
                    result.Message = checkResult.Message;
                    return result;
                }
                var checkVerifyCode = EncryptionLib.Encrypt(mcId + shopId);
                if (checkVerifyCode != verifyCode)
                {
                    _fileLog.Error("WeChatApiController | GetWechatParamQrCode | Error: Invalid verify code");
                    result.Message = "Invalid verify code";
                    return result;
                }
                var mkysProjectInfo = GetCurrentMatrixCloudProjectInfo(mcId);
                if (mkysProjectInfo == null || mkysProjectInfo.Id == 0)
                {
                    _fileLog.Error("WeChatApiController | GetWechatParamQrCode| ProjectInfo is null");
                    result.Message = "WeChatApiController | GetWechatParamQrCode| ProjectInfo is null";
                    return result;
                }
                var mcAccount = McAccountsBLL.Instance.GetModelList("ShopId=" + shopId + " and AccountType=1");
                if (mcAccount.Count == 0 || mcAccount[0].MxWechatParamQrCodeId <= 0)
                {
                    result.Status = true;
                    result.Data = string.Empty;
                    result.Message = "Success";
                    return result;
                }
                var resultQrCode = _matrixCloudCenterInterFuncBll.GetParamQrCodeById(mcAccount[0].MxWechatParamQrCodeId, mkysProjectInfo.PjMcId, mkysProjectInfo.PjSecret);
                result.Status = true;
                result.Data = resultQrCode == null ? string.Empty : resultQrCode.Data.LocalQrCodePath;
                result.Message = "Success";
                return result;
            }
            catch (Exception ex)
            {

                return new Result<string>
                {
                    Data = null,
                    Message = ex.Message,
                    Status = false
                };
            }
        }

    }
}
